package com.example.positioning.service;

import com.alibaba.fastjson.JSONObject;
import com.example.positioning.Task.CoordinateConversion;
import com.example.positioning.Task.WebSocketTask;
import com.example.positioning.pojo.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javafx.geometry.Point2D;

@Service
public class MqttDetail {
    double CHI=110947;
    @Autowired
    Room room;
    @Autowired
    WebSocketTask webSocketTask;
    public void detail(String topic,String str){
        if(topic.endsWith("location")) {
            System.out.println("室内："+str);
            detaillocalshinei(str);
        }
        else if(str.startsWith("$GNGLL"))
        {
            System.out.println("室外："+str);
            detaillocalshiwai(str);
        }

    }
    public double chushi(double a){
        int ede=((int)a)/100;
        double min=a-(ede*100);
        a=ede+(min/60);
        return a;
    }
    private void detaillocalshiwai(String str){
        System.out.println(str);
        String[]arr=str.split(",");
        Double x=Double.parseDouble(arr[3]);
        Double y=Double.parseDouble(arr[1]);
        x=chushi(x);
        y=chushi(y);
        double[]parr= CoordinateConversion.wgs84tobd09(x,y);
        x=parr[0];
        y=parr[1];
        if(webSocketTask.point==null) {
            webSocketTask.point = new Point2D(x, y);
            webSocketTask.inroom=false;
        }
    }
    private void detaillocalshinei(String str){
        JSONObject jsonObject=JSONObject.parseObject(str);
        JSONObject posionject=JSONObject.parseObject(jsonObject.getString("position"));
        Double x=posionject.getDouble("x");
        Double y=posionject.getDouble("y");
        if(!x.equals(Double.NaN)&&!y.equals(Double.NaN))
        {
            double len=Math.sqrt(x*x+y*y);
            double angle=getAngle(x,y);
            angle+=room.angle;
            double xcha=len*Math.cos(angle)/Math.cos(room.getZero().getY()/180*Math.PI)/CHI;
            double ycha=len*Math.sin(angle)/CHI;
            Point2D point=new Point2D(room.getZero().getX()+xcha,room.getZero().getY()+ycha);
            webSocketTask.point=point;
            webSocketTask.inroom=true;
        }
    }

    private double getAngle(double x,double y){
        double angle;
        angle= Math.atan2(y,x);
        if(y <0)angle+=Math.PI*2;
        return angle;
    }
}
